#!/usr/bin/env python3
import os
import json
import importlib
import logging
from typing import List, Tuple

class NetworkDiagnostics:
    """网络MCP服务器诊断工具"""
    
    def __init__(self, config_path: str):
        self.config_path = config_path
        self.logger = logging.getLogger("network_diagnostics")
        
    def run_full_check(self) -> bool:
        """执行完整诊断检查"""
        checks = [
            ("配置文件检查", self.check_config),
            ("依赖项检查", self.check_dependencies),
            ("权限检查", self.check_permissions)
        ]
        
        all_passed = True
        for name, check in checks:
            try:
                success, message = check()
                if success:
                    self.logger.info(f"✅ {name}: 通过")
                else:
                    self.logger.warning(f"⚠️ {name}: {message}")
                    all_passed = False
            except Exception as e:
                self.logger.error(f"❌ {name}错误: {str(e)}")
                all_passed = False
                
        return all_passed

    def check_config(self) -> Tuple[bool, str]:
        """检查配置文件有效性"""
        if not os.path.exists(self.config_path):
            return False, "配置文件不存在"
            
        try:
            with open(self.config_path) as f:
                config = json.load(f)
                
            required_fields = ['nodes', 'connections']
            for field in required_fields:
                if field not in config:
                    return False, f"缺少必要字段: {field}"
                    
            return True, "配置格式正确"
            
        except json.JSONDecodeError:
            return False, "配置文件不是有效的JSON格式"

    def check_dependencies(self) -> Tuple[bool, str]:
        """检查Python依赖包"""
        required = [
            ('networkx', '2.6.3'),
            ('psutil', '5.8.0'),
            ('aiohttp', '3.8.1')
        ]
        
        missing = []
        for pkg, version in required:
            try:
                module = importlib.import_module(pkg)
                if hasattr(module, '__version__') and module.__version__ < version:
                    missing.append(f"{pkg}>={version}")
            except ImportError:
                missing.append(pkg)
                
        if missing:
            return False, f"缺少或版本过低: {', '.join(missing)}"
        return True, "所有依赖已安装"

    def check_permissions(self) -> Tuple[bool, str]:
        """检查文件系统权限"""
        paths_to_check = [
            self.config_path,
            os.path.dirname(self.config_path),
            '/tmp'
        ]
        
        unwritable = []
        for path in paths_to_check:
            if not os.access(path, os.W_OK):
                unwritable.append(path)
                
        if unwritable:
            return False, f"无写入权限: {', '.join(unwritable)}"
        return True, "所有路径可访问"

if __name__ == "__main__":
    import sys
    logging.basicConfig(level=logging.INFO)
    
    if len(sys.argv) < 2:
        print("用法: ./network_diagnostics.py <config_path>")
        sys.exit(1)
        
    diag = NetworkDiagnostics(sys.argv[1])
    if not diag.run_full_check():
        print("❌ 诊断发现严重问题")
        sys.exit(1)
    print("✅ 所有检查通过")